<?php

include "CarverBase.php";

//验证请求的初始信息
if($_SERVER['REQUEST_METHOD'] == 'GET'){
    $params = array_merge($_POST,$_GET);
    $function = $params['action'];
    if(function_exists($function)){
        call_user_func($function,$params);
    }else{
        echo 'Function Not Exists!';
    }
}


//发布开发文档
function save($params){
    $content  = $params['content'];
    $last_time = $params['time'];
    
    if(time()- intval($last_time)  < 60 && $last_time){
        echo CarverBase::getInstance()->returnJson(5001,'很抱歉～，发布太频繁！');die;
    }
    

    $dir = __DIR__."/markdown/";
    if(!is_dir($dir)){
        mkdir($dir,0777);
    }
    
    $markdown_file = $dir .date("Y-m-d H:i:s",time())."-".mt_rand(1000,9999).".md";
    $result = file_put_contents($markdown_file,$content);
    
    if($result){
        echo CarverBase::getInstance()->returnJson(200,'恭喜你～，发布成功!');
        
    }else{
        echo CarverBase::getInstance()->returnJson(5001,'很遗憾～，发布失败!');
    }
}


//设置Redis缓存
function setCache($params){
    
    $key  = $params['key'];
    $content  = $params['content'];
    $last_time = $params['time'];
    
    if(empty($key) || empty($content) || empty($last_time)){
        echo CarverBase::getInstance()->returnJson(5002,'Request parameter error!');die;
    }
    
    if(time()- intval($last_time)  < 30 && $last_time){
        echo CarverBase::getInstance()->returnJson(5002,'Request too often!');die;
    }
    
    //初始化Redis连接
    $redis = CarverBase::getInstance()->initRedis();
    
    if($redis->ping()){
        $redis->setex($key,604800,$content);
        echo CarverBase::getInstance()->returnJson(200,'OK!');
    }else{
        echo CarverBase::getInstance()->returnJson(5001,'ERROR!');
    }
}

//获取Redis缓存
function getCache($params){
    $key  = $params['key'];
    $last_time = $params['time'];
    
    if(empty($key) || empty($last_time)){
        echo CarverBase::getInstance()->returnJson(5002,'Request parameter error!');die;
    }
    
    if(time()- intval($last_time)  < 60 && $last_time){
        echo CarverBase::getInstance()->returnJson(5002,'Request too often!');die;
    }
    
    //初始化Redis连接
    $redis = CarverBase::getInstance()->initRedis();
    
    if($redis->ping()){
        $exist_data = $redis->exists($key);
        if(!$exist_data){
            echo CarverBase::getInstance()->returnJson(5003,'The requested key does not exist!');
        }else{
            // $result['resource'] = $redis->get($key);
            $result['resource'] = CarverBase::getInstance()->initMysql();
            echo CarverBase::getInstance()->returnJson(200,'OK!',$result);
        }
    }else{
        echo CarverBase::getInstance()->returnJson(5001,'ERROR!');
    }
}








